<template>
  <canvas canvas-id="canvas"></canvas>
</template>

<script>
  import { mapState } from 'vuex'
  
  const db = uniCloud.database()
  const dbCmd = db.command
  const $ = dbCmd.aggregate
  
  import { getUserInfoById } from "@/api/platform/user.js"
  
  export default {
    name: "share-script",
    data() {
      return {
        gameMembersAvatar: [],
        type: '',
        QRcode: '',
        
        cover: '',
        name: '',
        standardPlayers: '',
        playTime: '',
        difficulty: '',
        shareText: '',
        price: '',
        userName: '',
        userAvatar: '',
        shareManId: '',
        userText: '',
        QRCodeText: '',
        needCount: '',
        needCountText: '',
        gameMembers: '',
        
        motorcadeRes: null,
        scriptRes: null
      }
    },
    props: {
      motorcadeId: {
        type: String,
        default: ''
      },
      scriptId: {
        type: String,
        default: ''
      }
    },
    computed: {
      ...mapState(['userInfo']),
      
      formatJoinTags() {
        return arr => arr?.map((item) => item.name).join('、')
      },
      getShareText() {
        let str = ''
        if (this.scriptRes?.maleCount) {
          str = str.concat(this.scriptRes.maleCount + '男')
        }
        if (this.scriptRes?.femaleCount) {
          str = str.concat(this.scriptRes.femaleCount + '女')
        }
        if (this.scriptRes?.classTags) {
          str = str.concat('、' +  this.formatJoinTags(this.scriptRes.classTags) || '-')
        }
        return str
      },
    },
    async created() {
      // console.clear();
      console.log("name: ", this.$options.name);
      uni.showLoading({ mask: true })
      if (this?.scriptId) {
        this.type = 'script'
        await this.getData2()
      } else {
        this.type = 'motorcade'
        await this.getData1()
      }
      await this.getQRUrl()
      await this.draw()
      uni.hideLoading()
    },
    methods: {
      async draw() {
        try {
          var [err, cover] = await uni.getImageInfo({
            src: this.cover
          })
          if (err) {
            console.log(1);
            throw err
          }
      
          var [err, icon1] = await uni.getImageInfo({
            src: 'https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_renshu@2x.png'
          })
          if (err) {
            console.log(2);
            throw err
          }
          var [err, icon2] = await uni.getImageInfo({
            src: 'https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_shijian@2x.png'
          })
          if (err) {
            console.log(3);
            throw err
          }
          var [err, icon3] = await uni.getImageInfo({
            src: 'https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_nandu@2x.png'
          })
          if (err) {
            console.log(4);
            throw err
          }
          
          var [err, userAvatar] = await uni.getImageInfo({
            src: this.userAvatar
          })
          if (err) {
            console.log(5);
            throw err
          }
          
          var [err, QRcode] = await uni.getImageInfo({
            src: this.QRcode
          })
          if (err) {
            console.log(6);
            throw err
          }
          
          if (this.type === 'motorcade') {
            for (let item of this.gameMembers) {
              var [err, avatar] = await uni.getImageInfo({
                src: item.avatar
              })
              if (err) {
                console.log(7);
                throw err
              }
              this.gameMembersAvatar.push(avatar)
            }
          }
          
          const canvasW = uni.upx2px(630)
          // const canvasH = uni.upx2px(1052)
          const canvasH = uni.upx2px(950)
          const coverW = uni.upx2px(570)
          const coverH = this.type === 'script' ? uni.upx2px(718 - 100) : uni.upx2px(588 - 100)
          const long100 = uni.upx2px(100)
          const long90 = uni.upx2px(90)
          const long80 = uni.upx2px(80)
          const long70 = uni.upx2px(70)
          const long60 = uni.upx2px(60)
          const long50 = uni.upx2px(50)
          const long40 = uni.upx2px(40)
          const long30 = uni.upx2px(30)
          const long26 = uni.upx2px(26)
          const long24 = uni.upx2px(24)
          const long20 = uni.upx2px(20)
          const long16 = uni.upx2px(16)
          const long10 = uni.upx2px(10)
          const long8 = uni.upx2px(8)
          const long6 = uni.upx2px(6)
          const long5 = uni.upx2px(5)
          const long4 = uni.upx2px(4)
          const long3 = uni.upx2px(3)
      
          const ctx = uni.createCanvasContext("canvas", this)
          ctx.clearRect(0, 0, canvasW, canvasH)
          
          /* 画布背景 */
          // ctx.fillStyle = 'rgba(255, 255, 255, 0)'
          // ctx.fillRect(0, 0, canvasW, canvasH)
          ctx.save()
          ctx.beginPath()
          ctx.setFillStyle('white')
          ctx.arc(long20, long20, long20, 1 * Math.PI, 1.5 * Math.PI)
          ctx.arc(canvasW - long20, long20, long20, 1.5 * Math.PI, 0)
          ctx.arc(canvasW - long20, canvasH - long20, long20, 0, 0.5 * Math.PI)
          ctx.arc(long20, canvasH - long20, long20, 0.5 * Math.PI, 1 * Math.PI)
          ctx.fill()
          ctx.closePath()
          ctx.clip()
          ctx.restore()
      
          /* 剧本封面 */
          ctx.save()
          ctx.beginPath()
          ctx.arc(long50, long50, long20, 1 * Math.PI, 1.5 * Math.PI)
          ctx.arc(canvasW - long50, long50, long20, 1.5 * Math.PI, 0)
          ctx.arc(canvasW - long50, coverH + long10, long20, 0, 0.5 * Math.PI)
          ctx.arc(long50, coverH + long10, long20, 0.5 * Math.PI, 1 * Math.PI)
          ctx.closePath()
          ctx.clip()
          ctx.drawImage(cover.path, long30, long30, coverW, coverH)
          ctx.restore()
      
          let startHeight = coverH + long60
          /* 剧本名 */
          ctx.font = 'normal bold 40px sans-serif'
          ctx.setTextBaseline('top')
          ctx.setFontSize(uni.upx2px(36))
          ctx.setFillStyle('#000000')
          ctx.fillText(this.name, long30, startHeight - long10)
          let nameW = ctx.measureText(this.name).width + long20
          /* 小字 */
          ctx.font = 'normal normal 40px sans-serif'
          ctx.setFontSize(long26)
          ctx.setFillStyle('#c1c1c1')
          let s1W = long26 + long8 + ctx.measureText(this.standardPlayers).width
          let s2W = long26 + long8 + ctx.measureText(this.playTime).width
          let s3W = long26 + long8 + ctx.measureText(this.difficulty).width
          let gap = long60
          if (coverW * 0.45 < nameW) {
            gap = (coverW - nameW - s1W - s2W -s3W) / 2
          }
          s1W += gap
          s2W += gap
          let sW = canvasW - long30 - s1W - s2W - s3W
          ctx.drawImage(icon1.path, sW, startHeight + long4, long26, long26)
          ctx.fillText(this.standardPlayers, sW + long26 + long8, startHeight + long3)
          ctx.drawImage(icon2.path, sW + s1W, startHeight + long4, long26, long26)
          ctx.fillText(this.playTime, sW + s1W + long26 + long8, startHeight + long3)
          ctx.drawImage(icon3.path, sW + s1W + s2W, startHeight + long4, long26, long26)
          ctx.fillText(this.difficulty, sW + s1W + s2W + long26 + long8, startHeight + long3)
      
          startHeight += long60
          /* 蓝字 */
          ctx.setFillStyle('#6667FF')
          ctx.setFontSize(long24)
          ctx.fillText(this.shareText, long40, startHeight)
          let borderW = ctx.measureText(this.shareText).width
          /* 蓝框 */
          ctx.setStrokeStyle('#6667FF')
          ctx.save()
          ctx.beginPath()
          ctx.arc(long30 + long6, startHeight - long4, long6, 1 * Math.PI, 1.5 * Math.PI)
          ctx.arc(long30 + long8 + borderW + long10, startHeight - long4, long6, 1.5 * Math.PI, 0)
          ctx.arc(long30 + long8 + borderW + long10, startHeight + long30, long6, 0, 0.5 * Math.PI)
          ctx.arc(long30 + long6, startHeight + long30, long6, 0.5 * Math.PI, 1 * Math.PI)
          ctx.closePath()
          ctx.stroke()
          ctx.clip()
          ctx.restore()
          /* 价格 */
          ctx.setFontSize(long26)
          ctx.setFillStyle('#FF5673')
          let priceW = ctx.measureText(this.price).width
          ctx.fillText(this.price, canvasW - long30 - priceW, startHeight)
          
          if (this.type === 'motorcade') {
            startHeight += long60
            /* 分割线1 */
            ctx.beginPath()
            ctx.setLineWidth(1)
            ctx.setLineDash([2, 2], 0);
            ctx.moveTo(long30, startHeight)
            ctx.setStrokeStyle('#979797')
            ctx.lineTo(canvasW - long30, startHeight)
            ctx.stroke()
            ctx.closePath()
            
            startHeight += long20
            /* 成员头像 */
            let sCircleCenterX = long50 + long5
            let sCircleCenterY = startHeight + long20 + long5
            for (let i = 0; i < this.gameMembersAvatar.length; i++) {
              let avatar = this.gameMembersAvatar[i].path
              
              ctx.save()
              ctx.beginPath()
              ctx.arc(sCircleCenterX + long60 * i, sCircleCenterY, long20 + long5, 0, 2 * Math.PI)
              ctx.clip()
              ctx.closePath()
              ctx.drawImage(avatar, long30 + long60 * i, startHeight, long50, long50)
              ctx.restore()
            }
            sCircleCenterX += long60 * this.gameMembersAvatar.length
            ctx.setLineWidth(1)
            ctx.setLineDash([3, 3], 0);
            ctx.font = 'normal bold 40px sans-serif'
            ctx.setFontSize(long26)
            ctx.setTextAlign('center')
            let text = '?'
            let textW = ctx.measureText(text).width
            for (let i = 0; i < this.needCount; i++) {
              ctx.beginPath()
              ctx.arc(sCircleCenterX + long60 * i, sCircleCenterY, long20 + long5, 0, 2 * Math.PI)
              ctx.setStrokeStyle('#FF5673')
              ctx.stroke()
              ctx.setFillStyle('#D8D8D8')
              ctx.fill()
              ctx.closePath()
              ctx.setFillStyle('#FF5673')
              ctx.fillText(text, sCircleCenterX + long60 * i, sCircleCenterY - long16)
            }
            ctx.font = 'normal normal 40px sans-serif'
            ctx.setTextAlign('left')
            
            startHeight += long10
            /* 缺人数 */
            ctx.setFontSize(long24)
            ctx.setFillStyle('#FF5673')
            ctx.fillText(this.needCountText, long30, startHeight + long50 + long8)
            
            startHeight += long40
          }
      
          startHeight += long60
          /* 分割线2 */
          ctx.beginPath()
          ctx.setLineWidth(1)
          ctx.setLineDash([2, 2], 0);
          ctx.moveTo(long30, startHeight)
          ctx.setStrokeStyle('#979797')
          ctx.lineTo(canvasW - long30, startHeight)
          ctx.stroke()
          ctx.closePath()
      
          startHeight += long30
          /* 分享人头像 */
          ctx.save()
          ctx.beginPath()
          ctx.arc(long30 + long20 +long40 + long4, startHeight + long40 + long8, long40, 0, 2 * Math.PI)
          ctx.clip()
          ctx.closePath()
          ctx.drawImage(userAvatar.path, long50, startHeight + long8, long80, long80)
          ctx.restore()
          /* 分享人名称 */
          ctx.setTextBaseline('top')
          ctx.setFontSize(long26)
          ctx.setFillStyle('#000000')
          ctx.fillText(this.userName, long100 + long50, startHeight + long10 + long8)
          ctx.setFontSize(long24)
          ctx.setFillStyle('#c1c1c1')
          ctx.fillText(this.userText, long100 + long50, startHeight + long50 + long8)
          /* 二维码 */
          let QRcodeSize = long100 + long30
          ctx.drawImage(QRcode.path, canvasW - long100 - long90 - long5, startHeight - long20, QRcodeSize, QRcodeSize)
          /* 竖向文字 */
          ctx.setFontSize(uni.upx2px(16))
          ctx.setFillStyle('#828282')
          let QRcodeText = this.QRCodeText
          for (let i = 0; i < QRcodeText.length; i++) {
            ctx.fillText(QRcodeText[i], canvasW - long60 + long3, startHeight + long20 * i)
          }
          let QRcodeTextW = ctx.measureText(QRcodeText[0]).width
          /* 灰框 */
          ctx.beginPath()
          ctx.setLineDash([0, 0], 0);
          ctx.setStrokeStyle('#dcdcdc')
          ctx.moveTo(canvasW - long60 - long10, startHeight - long20 + QRcodeSize / 2)
          ctx.lineTo(canvasW - long60 - long5, startHeight - long20 + QRcodeSize / 2 - long8)
          ctx.lineTo(canvasW - long60 - long5, startHeight - long10)
          ctx.lineTo(canvasW - long30 - long5, startHeight - long10)
          ctx.lineTo(canvasW - long30 - long5, startHeight - long30 + QRcodeSize)
          ctx.lineTo(canvasW - long60 - long5, startHeight - long30 + QRcodeSize)
          ctx.lineTo(canvasW - long60 - long5, startHeight - long20 + QRcodeSize / 2 + long8)
          ctx.lineTo(canvasW - long60 - long10, startHeight - long20 + QRcodeSize / 2)
          ctx.stroke()
          ctx.closePath()
      
          ctx.draw(false, () => {
            let that = this
            setTimeout(function() {
              uni.canvasToTempFilePath({
                canvasId: "canvas",
                quality: 1,
                fileType: 'jpg',
                success: (res) => {
                  console.log('临时文件路径：', res);
                  that.$emit('completed', res.tempFilePath)
                },
                fail: (err) => {
                  console.log('8: ', err);
                },
                complete: () => {
                  uni.hideLoading()
                }
              }, that);
            }, 200);
          })
        } catch (e) {
          uni.hideLoading()
          console.error(e)
        }
      },
      
      async getQRUrl() {
        if (this.type === 'script') {
          this.QRcode = `${ this.$cloudUrl }/genQRCode?text=${ encodeURIComponent('https://test.the3dspace.cn/scriptDetail?scriptId=' + this.scriptId + '&shareManId=' + this.shareManId) }`
        }
        if (this.type === 'motorcade') {
          this.QRcode = `${ this.$cloudUrl }/genQRCode?text=${ encodeURIComponent('https://test.the3dspace.cn/motorcadeDetail?motorcadeId=' + this.motorcadeId + '&from=gameroom' + '&shareManId=' + this.shareManId) }`
        }
        console.log(this.QRcode);
      },
      async getShareMan() {
        let avatar = ''
        let name = ''
        let shareManId = uni.getStorageSync('scriptKillShareManId')
        
        if (shareManId && shareManId != this.userInfo.id) {
          let res = await getUserInfoById({
            id: shareManId,
            showLoading: false
          })
          avatar = res.avatar
          name = res.nickname || res.username
          shareManId = res.id
        } else {
          avatar = this.userInfo.avatar
          name = this.userInfo.nickname || this.userInfo.username
          shareManId = this.userInfo.id
        }
        
        this.userAvatar = avatar
        this.userName = name
        this.shareManId = shareManId
      },
      
      async getData2() { // 剧本
        this.scriptRes = await this.$dbHelper.getById("t3ds-script", this.scriptId, {
          showLoading: false,
          field: 'cover, name, standardPlayers, playTime, difficulty, price, maleCount, femaleCount, classTags'
        })
        
        this.cover = this.scriptRes?.cover || ''
        this.name = this.scriptRes?.name || ''
        
        this.standardPlayers = this.scriptRes?.standardPlayers || 0
        this.playTime = (this.scriptRes?.playTime || 0) + 'H'
        this.difficulty = this.scriptRes?.difficulty || '-'
        
        this.shareText = this.getShareText
        
        this.price = (this.scriptRes?.price || 0) / 100 + '元/位'
        
        // this.userName = this.userInfo.nickname || this.userInfo.username
        // this.userAvatar = this.userInfo.avatar
        await this.getShareMan()
        this.userText = '邀请您看好剧本'
        
        this.QRCodeText = '扫码看剧本'.split('')
      },
      
      async getGameMembersData() {
        let res = await this.$dbHelper.getList("t3ds-order", {
          showLoading: false,
          where: { _id: dbCmd.in(this.motorcadeRes.orderIds)},
          field: 'user_id'
        })
        let res1 = res.map(item => item.user_id)
        let res2 = await this.$dbHelper.getList("uni-id-users", {
          showLoading: false,
          where: { _id: dbCmd.in(res1)},
          field: '_id, avatar, nickname, username, id, comment, creditScore'
        })
        if (res2.length > 1) {
          let foo = {}
          for (let i = 0; i < res2.length; i++) {
            if (res2[i].id === this.motorcadeRes.id) {
              foo = res2[i]
              res2.splice(i, 1)
              break
            }
          }
          res2.unshift(foo);
        }
        return res2
      },
      async getData1() { // 车队
        this.motorcadeRes = await this.$dbHelper.getById("t3ds-subscribe-motorcade", this.motorcadeId, {
          showLoading: false,
          field: 'thumbnail, name, costPerPerson, minPlayers, currentMaleCount, currentFemaleCount, scriptId, orderIds, id'
        })
        this.scriptRes = await this.$dbHelper.getById("t3ds-script", this.motorcadeRes.scriptId, {
          showLoading: false,
          field: 'standardPlayers, playTime, difficulty, maleCount, femaleCount, classTags'
        })
        
        this.cover = this.motorcadeRes?.thumbnail || ''
        this.name = this.motorcadeRes?.name || ''
        
        this.standardPlayers = this.scriptRes?.standardPlayers || 0
        this.playTime = (this.scriptRes?.playTime || 0) + 'H'
        this.difficulty = this.scriptRes?.difficulty || '-'
        
        this.shareText = this.getShareText
        
        this.price = (this.motorcadeRes?.costPerPerson || 0) / 100 + '元/位'
        
        // this.userName = this.userInfo.nickname || this.userInfo.username
        // this.userAvatar = this.userInfo.avatar
        await this.getShareMan()
        this.userText = '邀请您加入车队'
        
        this.QRCodeText = '扫码看车队'.split('')
        
        this.needCount = this.motorcadeRes.minPlayers - this.motorcadeRes.currentMaleCount - this.motorcadeRes.currentFemaleCount || 0
        this.needCountText = `仅缺${ this.motorcadeRes.minPlayers - this.motorcadeRes.currentMaleCount - this.motorcadeRes.currentFemaleCount || 0 }位，赶快上车！`
        this.gameMembers = await this.getGameMembersData()
      }
    }
  }
</script>

<style scoped lang="scss">
  canvas {
    // margin-top: -120rpx;
    margin-top: -40rpx;
    width: 630rpx;
    height: 950rpx;
    background: #FFFFFF;
    border-radius: 20rpx;
    position: relative;
    z-index: 1;
  }
</style>
